//
//  HPYComposePictureView.swift
//  SwiftVVBo
//
//  Created by hepeiyong on 16/8/18.
//  Copyright © 2016年 hpyhn. All rights reserved.
//

import UIKit

// cell 可重用标示符
private let HPYComposePictureViewCellId = "HPYComposePictureViewCellId"
class HPYComposePictureView: UICollectionView {

    // 保存image 的数组
    var imageList:[UIImage] = [UIImage]()

    // 01 声明一个闭包
    var closure:(()->())?

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - 供外界调用的方法
    func addImages(image: UIImage){
        // 显示当前控件
        self.hidden = false
        // 添加到数组中
        imageList.append(image)
        // 刷新UI
        reloadData()
    }

    // MARK: - 设置视图
    private func setupUI(){
        // 隐藏当前控件
        self.hidden = true
        backgroundColor = UIColor.whiteColor()
        // 注册cell
        registerClass(HPYComposePictureViewCell.self, forCellWithReuseIdentifier: HPYComposePictureViewCellId)
        // 设置代理
        dataSource = self
        delegate  = self
        // 设置layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        // cell间距
        let cellMargin: CGFloat = 5
        // cell 宽高
        let cellWH: CGFloat = (SCREENW - 20 - 2*cellMargin)/3
        // 设置itemSize
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        // 设置垂直和水平间距
        layout.minimumInteritemSpacing = cellMargin
        layout.minimumLineSpacing = cellMargin
    }
}

extension HPYComposePictureView: UICollectionViewDataSource , UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        /*
         - 如果 显示为 0 或者为 9 没有加号图片
         - 反之 其他 后面 显示加号图片
         */
        let count = imageList.count
        if count == 0 || count == 9 {
            return count
        }
        return imageList.count + 1
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HPYComposePictureViewCellId, forIndexPath: indexPath) as! HPYComposePictureViewCell
        /*
         [1,2,3]  数组.count  3
         item =  0 , 1 ,2

         */
        // 除了0 和 9
        if imageList.count ==  indexPath.item {
            cell.image = nil
        }else {
            // 赋值
            cell.image = imageList[indexPath.item]

            // 实例化闭包
            cell.closure = {[weak self] in
                // 删除指定图片
                self?.imageList.removeAtIndex(indexPath.item)
                if self?.imageList.count == 0 {
                    // 隐藏当前控件
                    self?.hidden = true
                }
                // 刷新UI
                self?.reloadData()
            }
        }
        return cell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        // 如果不是0 张也不是 9张 最后一个是加号图片
        if imageList.count ==  indexPath.item{
            // 03执行闭包
            closure?()
        }
    }


}
// 自定义cell
class HPYComposePictureViewCell: UICollectionViewCell {
    // 声明一个闭包01
    var closure:(()->())?

    // 供外界调用
    var image: UIImage?{
        didSet{
            // 赋值
            // 加号图片
            if image == nil {
                bgImageView.image = UIImage(named: "compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                deleteButton.hidden = true
            }else {
                bgImageView.image = image
                // 解决cell 复用问题
                bgImageView.highlightedImage = nil
                deleteButton.hidden = false
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - 监听事件
    @objc private func buttonClick(){
        print("删除按钮点击")
        // 03
        closure?()
    }

    // MARK: - 设置视图
    private func setupUI(){

        // 添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(deleteButton)
        // 添加约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }

        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.trailing.equalTo(contentView)
        }
    }
    // MARK: - 懒加载控件
    private lazy var bgImageView: UIImageView = UIImageView()
    // 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        // 添加事件
        button.addTarget(self, action: #selector(HPYComposePictureViewCell.buttonClick), forControlEvents: UIControlEvents.TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        return button
    }()


}

